<template>
<div>
    <div>
        <el-button type="primary" @click="handleAdd" size="small" v-if="!smallPaginition">添加</el-button>
    </div>
    <el-table :data="data" style="width: 100%" stripe :height="500" v-loading="loading">
        <!-- <el-table-column prop="id" label="ID" width="80">
        </el-table-column> -->
        <el-table-column prop="name" label="角色">
        </el-table-column>
        <el-table-column prop="code" label="编码">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100" align="center" v-if="!smallPaginition">
            <template slot-scope="scope">

                <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" style="color:red" @click="handleDelete(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 10px;" @size-change="refresh" @current-change="refresh" :current-page.sync="page.current" :page-sizes="[5, 10, 20, 50]" :page-size.sync="page.pageSize" :layout="layout" :total="total" :small="smallPaginition">
    </el-pagination>

    <el-drawer :title="title" :visible.sync="dialogVisible" direction="rtl" :before-close="handleClose" :close-on-press-escape="false" :show-close="false" size="600px" :wrapperClosable="false">

        <el-container>
            <el-header>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="60px" :inline="true">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="ruleForm.name" style="width:200px" clearable size="small"></el-input>
                    </el-form-item>
                    <el-form-item label="编码" prop="code">
                        <el-input v-model="ruleForm.code" style="width:200px" clearable szie="small"></el-input>
                    </el-form-item>
                </el-form>
            </el-header>
            <el-main>
                <el-table v-loading="innerloading" ref="permissionTbl" :data="permissionData" :highlight-current-row="true" style="width: 100%" height="600" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="80">

                    </el-table-column>
                    <el-table-column prop="name" label="权限" width="150" sortable align="center">
                    </el-table-column>
                    <el-table-column prop="code" label="编码" width="300" align="center">
                        <template slot="header" slot-scope="scope">
                            <el-input v-model="search" size="mini" style="width: 200px;" placeholder="输入关键字搜索" clearable @clear="handleSearchClear">
                                <template slot="append">
                                    <el-button @click="handleSearchPermission"><i class="el-icon-search"></i></el-button>
                                </template>
                            </el-input>

                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
            <el-footer>
                <el-button type="primary" @click="handleConfirm">确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </el-footer>
        </el-container>
    </el-drawer>
</div>
</template>

<script>
import {
    addRole,
    deleteRole,
    getPageList,
    updateRole
} from "@/api/role"
import {
    getPermissionList
} from "@/api/user"
export default {
    name: "role",
    created() {
        this.refresh()
    },
    data() {
        return {
            innerloading: "",
            search: "",
            loading: false,
            title: "",
            permissionData: [],
            multipleSelection: [],
            layout: "total, sizes, prev, pager, next, jumper",
            smallPaginition: false,
            ruleForm: {
                id: null,
                name: "",
                code: "",
            },
            rules: {
                name: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }, ],
                code: [{
                    required: true,
                    message: '请输入角色编码',
                    trigger: 'blur'
                }, ],
            },
            data: null,
            dialogVisible: false,
            total: 0,
            page: {
                "current": 0,
                "pageSize": 20
            }
        }
    },
    mounted() {
        this.handleResize();
        window.addEventListener('resize', this.handleResize);
    },
    methods: {
        handleSearchClear() {
            this.$refs.permissionTbl.setCurrentRow()
        },
        scrollToRow(row) {
            setTimeout(() => {
                const scrollRow = this.$refs.permissionTbl.$el.querySelector('.el-table__row.current-row')
                if (scrollRow) {
                    scrollRow.scrollIntoView()
                }
            }, 100)
        },
        handleSearchPermission() {
            const row = this.permissionData.find(item => {
                return item.name == this.search
            })
            this.$refs.permissionTbl.setCurrentRow(row)
            this.scrollToRow(row)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        async handleEdit(row) {
            this.title = "修改角色"
            this.dialogVisible = true
            const that = this;

            setTimeout(async () => {
                that.innerloading = true
                await this.getPermissionListResult()
                this.multipleSelection = row.permissions
                this.ruleForm = JSON.parse(JSON.stringify(row))
                that.multipleSelection.forEach(item => {
                    const row = that.permissionData.find(inneritem => {
                        return inneritem.id == item.id
                    })
                    that.$refs.permissionTbl.toggleRowSelection(row, true)
                })
                that.innerloading = false
            }, 200)

        },
        handleResize() {
            if (document.body.clientWidth < 768) {
                this.smallPaginition = true
                this.layout = "prev, pager, next"

            } else {
                this.smallPaginition = false
                this.layout = "total, sizes, prev, pager, next, jumper"

            }
        },
        async getPermissionListResult() {
            const res = await getPermissionList({
                "current": 1,
                "pageSize": 999999
            })
            if (res.code == 200) {
                this.permissionData = res.data.records;
            } else {
                this.$message.error(res.message)
            }

        },
        async handleAdd() {
            this.title = "添加角色";
            this.multipleSelection = []
            const that = this

            setTimeout(async () => {
                that.innerloading = true
                await this.getPermissionListResult()
                that.innerloading = false
            }, 200)
            this.dialogVisible = true;
        },
        handleClose() {
            this.ruleForm.name = ""
            this.ruleForm.code = ""
            this.ruleForm.id = null
            this.title = ""
            this.multipleSelection = []
            this.$refs.ruleForm.clearValidate()
            this.dialogVisible = false
        },
        handleConfirm() {
            if (this.title == "添加角色") {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        this.ruleForm.permissions = JSON.parse(JSON.stringify(this.multipleSelection))
                        addRole(this.ruleForm).then(res => {
                            if (res.code == 200) {
                                this.$message.success("添加成功")
                                this.handleClose()
                                this.refresh()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    }
                })
            }
            if (this.title == "修改角色") {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        this.ruleForm.permissions = JSON.parse(JSON.stringify(this.multipleSelection))
                        updateRole(this.ruleForm).then(res => {
                            if (res.code == 200) {
                                this.$message.success("修改成功")
                                this.handleClose()
                                this.refresh()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    }
                })
            }

        },
        refresh() {
            this.loading = true
            getPageList(this.page).then(res => {
                if (res.code == 200) {
                    this.data = res.data.records;
                    this.total = res.data.total;
                } else {
                    this.$message.error(res.message)
                }
            }).finally(() => {
                this.loading = false
            })
        },
        handleDelete(row) {
            this.$confirm('确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteRole(row.id).then(res => {
                    if (res.code == 200) {
                        this.$message.success("已删除")
                        this.refresh();
                    } else {
                        this.$message.error(res.message)
                    }

                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }

    }

};
</script>

<style></style>
